package cn.hj.pay.controller;


import cn.hj.basic.constant.BaseConstant;
import cn.hj.basic.constant.PayConstant;
import cn.hj.order.domain.AdoptOrder;
import cn.hj.order.domain.ProductOrder;
import cn.hj.order.service.IAdoptOrderService;
import cn.hj.order.service.IProductOrderService;
import cn.hj.pay.domain.AlipayInfo;
import cn.hj.pay.domain.PayBill;
import cn.hj.pay.service.IAlipayInfoService;
import cn.hj.pay.service.IPayBillService;
import cn.hj.pay.utils.AlipayConfig;
import cn.hj.product.service.IProductService;
import cn.hj.quartz.service.IQuartzService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AlipayController {

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IAlipayInfoService alipayInfoService;

    @Autowired
    private IAdoptOrderService adoptOrderService;

    @Autowired
    private IProductOrderService productOrderService;

    @Autowired
    private IQuartzService quartzService;

    /**
     * 支付宝登录成功之后的异步通知接口
     * @param request
     */
    @PostMapping("/notify")
    public void notify(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        System.out.println("11111---------------------");
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        //拿到我的统一支付标识
        String  unionPaySn = params.get("out_trade_no");
        PayBill payBill = payBillService.loadByUnionPaySn(unionPaySn);
        AlipayInfo info = alipayInfoService.getByShopId(payBill.getShop_id());
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                info.getAlipay_public_key(),
                AlipayConfig.charset,
                AlipayConfig.sign_type); //调用SDK验证签名

        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = unionPaySn;
            //支付宝交易号
            String trade_no =request.getParameter("trade_no");

            //交易状态
            String trade_status =request.getParameter("trade_status");

            if(trade_status.equals("TRADE_FINISHED")){
                //.....
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //调整统一支付单的状态
                payBill.setState(1);
                payBill.setUpdateTime(new Date());
                payBillService.update(payBill);
                //记录已支付流水

                //通过businessType和businesskey修改某一个订单状态
                String businessType = payBill.getBusinessType();
                if (businessType.equals(PayConstant.ADOPT_ORDER)){//领养订单
                    AdoptOrder order = adoptOrderService.findById(payBill.getBusinessKey());
                    order.setState(1);
                    adoptOrderService.update(order);
                }else if (businessType.equals(PayConstant.SERVICE_ORDER)){//服务订单
                    ProductOrder productOrder = productOrderService.findById(payBill.getBusinessKey());
                    productOrder.setState(1);
                    productOrderService.update(productOrder);
                    // 删除支付超时定时任务
                    String jobName = BaseConstant.PAY_TIMEOUT_CANCEL_ADOPT + productOrder.getId();
                    quartzService.removeJob(jobName);
                    //@TODO 添加超时未确认定时任务  7
                }else {

                }
            }

        }else {//验证失败

        }
    }

}
